import { MemSubject } from '@gnlab/utils/rx'
import ApplyByPersonCard from '@/desktop/components/ApplyByPersonCard'
import ChooseContacts from '@/desktop/components/ChooseContacts'
import { SaveMatchReplyModal } from '@/desktop/views/app-center/robot-settings/save-match-reply'
import { useStreams } from '@/lib/utils'
import services from '@/services'
import type { ChatRecord } from '@/services/contact-chat'
import { ContactType } from '@/services/contacts'
import { type HistoryItem as RobotHistoryItem } from '@/services/features/robot'

/**
 * 多条 record / action 都可能触发的对话框组件，出于性能考虑，由上级只渲染一次
 * 各 record / action 调用 modals.xxx.next() 来传递参数开启对话框
 */

export const modals = {
  applyByPersonCard: new MemSubject<{ senderWxid: string; personCardUserId: string } | null>(null),
  forward: new MemSubject<ChatRecord[] | null>(null),
  saveToRobot: new MemSubject<{ profileId: number; records: RobotHistoryItem[] } | null>(null),
}

export function RecordModals() {
  const [applyByPersonCard, forward, saveToRobot] = useStreams(
    modals.applyByPersonCard,
    modals.forward,
    modals.saveToRobot,
  )

  return <>
    <ApplyByPersonCard
      {...applyByPersonCard}
      onFinish={() => modals.applyByPersonCard.next(null)}
    />

    <ChooseContacts
      visible={forward !== null}
      title="分别发送给"
      types={forwardContactTypes}
      limit={9}
      onFinish={contacts => {
        void services.chat.forward(forward!, contacts)
        modals.forward.next(null)
      }}
      onCancel={() => modals.forward.next(null)}
    />

    <SaveMatchReplyModal
      profileId={saveToRobot?.profileId ?? -1}
      records={saveToRobot?.records ?? null}
      onFinish={() => modals.saveToRobot.next(null)}
    />
  </>
}

const forwardContactTypes = [ContactType.external, ContactType.group, ContactType.internal]
